package com.ljy.my_study.java.时间轮;

import lombok.Data;

import java.util.List;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @description: 时间轮算法
 * @author: James
 * @create: 2022-04-16 19:23
 */
@Data
public class TimeRound {

    private int[] units={60,60};

    public TimeRound(Integer time, TimeUnit unit) {
        this.time = time;
        this.unit = unit;

        int size=0;
        if(TimeUnit.HOURS==unit){
            size=units[0];
        }else if(TimeUnit.MINUTES==unit){
            size=units[1];
        }
        this.next = new TimeRound[size];
    }

    /**
     * 所在时间单位的数
     */
    private Integer time;

    /**
     * 时间单位
     */
    private TimeUnit unit;

    /**
     * 下一个时间轮
     */
    private TimeRound[] next;

    private int size;

    private Queue<Task> tasks=null;

    public int[] getUnits() {
        return units;
    }

    public void setUnits(int[] units) {
        this.units = units;
    }

    public Integer getTime() {
        return time;
    }

    public void setTime(Integer time) {
        this.time = time;
    }

    public TimeUnit getUnit() {
        return unit;
    }

    public void setUnit(TimeUnit unit) {
        this.unit = unit;
    }

    public TimeRound[] getNext() {
        return next;
    }

    public void setNext(TimeRound[] next) {
        this.next = next;
    }

    public Queue<Task> getTasks() {
        return tasks;
    }

    public void setTasks(Queue<Task> tasks) {
        this.tasks = tasks;
    }

    public boolean addTask(Task task){
        if(!unit.equals(TimeUnit.SECONDS)){
            return false;
        }
        if(tasks==null){
            synchronized(this){
                if(tasks==null){
                    tasks=new ArrayBlockingQueue<>(10);
                }
            }
        }
        tasks.offer(task);
        return true;
    }
}
